package com.project.providers;

import java.util.ArrayList;
import java.util.List;

import com.project.bean.Features;
import com.project.bean.FinalProject;
import com.project.bo.FeaturesBO;
import com.project.structures.json.FeaturesMap;
import com.project.structures.util.FileUtils;
import com.project.structures.util.JSONUtils;
import com.project.structures.util.XMLUtils;
import com.project.structures.xml.RuleXML;

public class FeaturesProvider {
	
	private List<Features> featuresBD;
	private FeaturesMap featuresMap;

	private static FeaturesProvider instance;
	private static Boolean initiated = Boolean.FALSE;
	
	public static FeaturesProvider getInstance() {
		if (instance == null) {
			instance = new FeaturesProvider();
		}
		
		return instance;
	}
	
	private FeaturesProvider() {
		this.featuresBD = new ArrayList<Features>();
		this.featuresMap = new FeaturesMap();
	}
	
	public void initProvider() {
		FeaturesBO featBO = FeaturesBO.getInstance();
		
		featuresBD = featBO.getFeatures();
		
		initiated = Boolean.TRUE;
		
		fillProvider();
	}
	
	public void fillProvider() {
		
		if (initiated) {
			boolean persist = Boolean.FALSE;
			featuresMap = new FeaturesMap();
			featuresMap.addAllFeature(featuresBD);
			
			JSONUtils.marshalToFile(featuresMap);
			
			for (Features feature : featuresMap.getFeatures()) {
				if (!FileUtils.existsFile(feature.getFeatureLink() + ".jsp")) {
					
					String content = FinalProject.getExampleJSP();
					content = content.replace("#link#", feature.getFeatureLink());
					
					FileUtils.writeFile(feature.getFeatureLink() + ".jsp", content);
				}
				
				if (!FinalProject.getUrlrewriterNodes().contains("(/"+feature.getFeatureLink()+")$")) {
					RuleXML rule = new RuleXML();
					rule.setFrom("(/"+feature.getFeatureLink()+")$");
					rule.setTo("contents/templates/features/" + feature.getFeatureLink() + ".jsp");
					
					FinalProject.getUrlrewriterNodes().addRule(rule);
					persist = Boolean.TRUE;
				}
			}
			
			if(persist) {
				XMLUtils.marshalToFile(FinalProject.getUrlrewriterNodes());
			}
		}
		
		FinalProject.setFeaturesMAP(featuresMap);
	}
	
	public void reloadProvider() {
		
	}	
}
